package cn.jee.redis;

import cn.jee.redis.domain.Stu;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.resps.Tuple;

import java.util.List;

import java.util.ArrayList;
import java.util.Set;
public class StuMis {
    private Jedis jedis;   
    public StuMis(){
        jedis=new Jedis();
    }
    //清空数据库
    public void clear(){
      jedis.flushAll();
    }
    //产生一个学生学号
    public long newId(){
      return jedis.incr("stu:id");
    }
    /**
     给Stu一个学号，然后保存在stu:学号的具体值的hash表中
     同时保存java成绩在sorted set中
     保存math成绩在sorted set中
     */
    
    public void add(Stu stu){
      if (stu.getId() == 0) {
        stu.setId(newId());
      }

      String key = "stu:" + stu.getId();
      jedis.hset(key, "id", String.valueOf(stu.getId()));
      jedis.hset(key, "username", stu.getUsername());
      jedis.hset(key, "java", String.valueOf(stu.getJava()));
      jedis.hset(key, "math", String.valueOf(stu.getMath()));

      // 添加到Java成绩排序集合
      jedis.zadd("java_scores", stu.getJava(), key);
      // 添加到Math成绩排序集合
      jedis.zadd("math_scores", stu.getMath(), key);
    }
    /**数学成绩最高的5个人的姓名*/
    public String[] top5ByMath(){
      Set<Tuple> top5 = (Set<Tuple>) jedis.zrevrangeWithScores("math_scores", 0, 4); // 数学成绩从高到低前5
      String[] names = new String[5];
      int i = 0;
      for (Tuple tuple : top5) {
        String key = tuple.getElement();
        names[i++] = jedis.hget(key, "username");
      }

      return names;
    }
    /**成绩在min和max之间的java成绩*/
    public double[] betweenJava(double min,double max){
      Set<String> keys = (Set<String>) jedis.zrangeByScore("java_scores", min, max);
      double[] scores = new double[keys.size()];
      int i = 0;

      for (String key : keys) {
        scores[i++] = Double.parseDouble(jedis.hget(key, "java"));
      }

      return scores;
    }
    /**按学号查找，没有返回null*/
    public Stu findById(long id){
      String key = "stu:" + id;
      if (!jedis.exists(key)) {
        return null;
      }

      Stu stu = new Stu();
      stu.setId(id);
      stu.setUsername(jedis.hget(key, "username"));
      stu.setJava(Double.parseDouble(jedis.hget(key, "java")));
      stu.setMath(Double.parseDouble(jedis.hget(key, "math")));

      return stu;
    }
    /**按java成绩从低到高分页查询*/
    public List<Stu> pageByJava(int page,int size){
      long start = (page - 1) * size;
      long end = start + size - 1;

      Set<String> keys = (Set<String>) jedis.zrange("java_scores", start, end);
      List<Stu> students = new ArrayList<>();

      for (String key : keys) {
        students.add(findById(Long.parseLong(key.split(":")[1])));
      }

      return students;
    }
}